from base64 import b64decode

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render, redirect

from polls.captcha import Captcha
from polls.models import Subject, Teacher, User
from polls.utils import random_text, to_md5_hex, check_username, check_password


def index(request):
    """首页（获取所有学科）"""
    queryset = Subject.objects.all()
    context = {
        'subjects': queryset
    }
    return render(request, 'subjects.html', context)


def show_teachers(request):
    """显示指定学科的老师"""
    try:
        sno = request.GET['sno']
        subject = Subject.objects.get(no=sno)
        queryset = Teacher.objects.filter(subject__no=sno)
        context = {
            'subject': subject,
            'teachers': queryset
        }
        return render(request, 'teachers.html', context)
    except (KeyError, ValueError, Subject.DoesNotExist):
        return redirect('/')


def praise_or_criticize(request):
    """好评或差评"""
    if request.session.get('userid') is None:
        data = {'code': 10002, 'message': '请先登录'}
    else:
        tno = request.GET.get('tno', '0')
        try:
            teacher = Teacher.objects.get(no=tno)
            if request.path.startswith('/praise'):
                teacher.good_count += 1
            else:
                teacher.bad_count += 1
            teacher.save()
            data = {'code': 10000, 'message': '操作成功'}
        except (ValueError, Teacher.DoesNotExist):
            data = {'code': 10001, 'message': '操作失败'}
    return JsonResponse(data)


def login(request):
    """登录"""
    backurl = request.GET.get('backurl', '')
    hint = ''
    if request.method == 'POST':
        code_from_user = request.POST.get('captcha', '0').lower()
        code_from_serv = request.session.get('code', '1').lower()
        if code_from_serv == code_from_user:
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            if check_username(username) and check_password(password):
                password = to_md5_hex(password)
                user = User.objects.filter(username=username,
                                           password=password).first()
                if user:
                    request.session['userid'] = user.no
                    request.session['username'] = user.username
                    backurl = b64decode(backurl).decode() if backurl else '/'
                    return redirect(backurl)
                else:
                    hint = '用户名或密码错误'
            else:
                hint = '请输入有效的用户名和密码'
        else:
            hint = '请输入正确的验证码'
    context = {
        'hint': hint,
        'backurl': backurl
    }
    return render(request, 'login.html', context)


def logout(request):
    """注销（退出登录）"""
    request.session.flush()
    return redirect('/')


def get_captcha(request):
    """获取验证码图片"""
    code = random_text()
    image_data = Captcha.instance().generate(code)
    request.session['code'] = code
    return HttpResponse(image_data, content_type='image/png')


# def index(request: HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜',
#               '榴莲', '火龙果', '猕猴桃', '山竹']
#     context = {
#         'fruits': sample(fruits, 3),
#         'greeting': '你好，世界'
#     }
#     return render(request, 'index.html', context)


# def index(request: HttpRequest):
#     fruits = ['苹果', '香蕉', '菠萝', '草莓', '西瓜',
#               '榴莲', '火龙果', '猕猴桃', '山竹']
#     content = StringIO()
#     content.write('<h2>今日推荐水果</h2>\r\n')
#     content.write('<hr>\r\n')
#     content.write('<ul>\r\n')
#     for fruit in sample(fruits, 3):
#         content.write(f'\t<li>{fruit}</li>\r\n')
#     content.write('</ul>\r\n')
#     return HttpResponse(content.getvalue())
